//
//  SDDotAnimationView.m
//  SKinDiary
//
//  Created by pcyang on 16/6/26.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDDotAnimationView.h"

@interface SDDotAnimationView ()
@property(nonatomic, strong) NSMutableArray *arrayCircle;
@property(readwrite, nonatomic) BOOL isAnimating;

- (void)addCircles;
- (UIView *)createCircleWithRadius:(CGFloat)radius color:(UIColor *)color positionX:(CGFloat)x;
@end

@implementation SDDotAnimationView

- (id)init {
    self = [super initWithFrame:CGRectZero];
    if (self) {
        
        self.arrayCircle = [NSMutableArray array];
        self.numberOfCircles = 3;
        self.internalSpacing = 6;
        self.duration = 0.416f;
        self.radius = 4;
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(appDidEnterForeground:)
                                                     name:UIApplicationWillEnterForegroundNotification
                                                   object:nil];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)initViews {
    [self addCircles];
}

- (UIView *)createCircleWithRadius:(CGFloat)radius color:(UIColor *)color positionX:(CGFloat)x {
    UIView *circle = [[UIView alloc] initWithFrame:CGRectMake(x, 0, radius * 2, radius * 2)];
    circle.backgroundColor = color;
    circle.layer.cornerRadius = radius;
    circle.translatesAutoresizingMaskIntoConstraints = NO;
    return circle;
}

- (void)addCircles {
    for (NSUInteger i = 0; i < self.numberOfCircles; i++) {
        UIColor *color = [UIColor grayColor];
        if (self.delegate && [self.delegate respondsToSelector:@selector(dotView:circleBackgroundColorAtIndex:)]) {
            color = [self.delegate dotView:self circleBackgroundColorAtIndex:i];
        }
        UIView *circle = [self createCircleWithRadius:self.radius
                                                color:color
                                            positionX:(i * ((2 * self.radius) + self.internalSpacing))];
        [circle setTransform:CGAffineTransformMakeScale(1, 1)];
        [self addSubview:circle];
        [self.arrayCircle addObject:circle];
        self.width = circle.right;
    }
}

- (void)startAnimating {
    if (self.isAnimating) {
        return;
    }
    [self _startAnimationAtIndex:0 delay:0.0f];
    [self _startAnimationAtIndex:1 delay:self.duration/2];
    [self _startAnimationAtIndex:2 delay:self.duration];
}


- (void)stopAnimating {
    [self.arrayCircle enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        UIView *cirle = obj;
        [cirle.layer removeAllAnimations];
    }];
    self.isAnimating = NO;
}

- (void)_startAnimationAtIndex:(NSInteger)index delay:(CGFloat)seconds{
    if (![self _isValidIndex:index]) {
        return;
    }
    if (!self.isAnimating) {
        self.isAnimating = YES;
    }
    UIView *circle = [self.arrayCircle objectAtIndex:index];
    CAKeyframeAnimation *animation = [self _createKeyFrameAnimationWithDuration:self.duration];
    animation.beginTime = CACurrentMediaTime() + seconds;
    [circle.layer addAnimation:animation forKey:@"scale"];
}

- (BOOL)_isValidIndex:(NSInteger)index {
    if (index < 0 || index >= [self.arrayCircle count]) {
        return NO;
    }
    return YES;
}


- (CAKeyframeAnimation*)_createKeyFrameAnimationWithDuration:(CGFloat)duration{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    animation.duration = duration*1.5f;
    animation.cumulative = NO;
    animation.repeatCount = HUGE_VALF;
    //动画结束后，delay 0.5duration 再开始
    animation.values = [NSArray arrayWithObjects:
                        [NSNumber numberWithFloat:1.0f],
                        [NSNumber numberWithFloat:1.5f],
                        [NSNumber numberWithFloat:1.0f],
                        [NSNumber numberWithFloat:1.0f],nil];
    animation.keyTimes = [NSArray arrayWithObjects:     // Relative timing values for the 3 keyframes
                          [NSNumber numberWithFloat:0.0f],
                          [NSNumber numberWithFloat:duration/2],
                          [NSNumber numberWithFloat:duration],
                          [NSNumber numberWithFloat:duration*1.5f], nil];
    animation.timingFunctions = [NSArray arrayWithObjects:
                                 [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],	// from keyframe 1 to keyframe 2
                                 [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                 [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear], nil];	// from keyframe 2 to keyframe 3
    animation.removedOnCompletion = YES;
    return animation;
    
}

- (void)appDidEnterForeground:(NSNotification *)notifaction {
    if (self.isAnimating) {
        [self stopAnimating];
        [self startAnimating];
    }
}

@end

